package project.login;


import org.json.JSONException;
import org.json.JSONObject;
import project.Dao.UserDao;
import project.Domain.User;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;

import static java.lang.System.out;

public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doGet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了doPost");
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了login");
        try {
            processlogin(request, response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void processlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException {

        String loginName = request.getParameter("login_name");
        String loginPassword = request.getParameter("login_password");
        request.setCharacterEncoding("UTF-8");
        out.println("页面传递过来的数据:" + loginName + " " + loginPassword);
        JSONObject json = new JSONObject();

        if (loginName != null && loginPassword != null) {
            UserDao userDao = new UserDao();
            User user = userDao.login(loginName);
            int leaderID = userDao.getLeaderID(loginName);
//            判断用户是否存在
            if (user != null) {
//                用户存在，判断是否登录成功
                json.put("user_exist", 1);
                if (user.getPassword().equals(loginPassword)) {
                    json.put("login_msg", 200);
                    json.put("user_name", user.getName());
                    json.put("user_role", user.getRole());
                    json.put("user_id", user.getId());
                    json.put("user_login_name", user.getUsername());
                    json.put("hasLeader", leaderID > 0 ? "yes" : "no");
                } else {
                    //                密码错误
                    json.put("login_msg", "密码错误");
                }
            } else {
                //            用户不存在
                json.put("login_msg", "用户不存在！");
            }
        }
        out.println(json);
        //将响应消息返回页面
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();

    }
}
